package com.angel.web.health;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.angel.core.Constants;
import com.angel.core.util.FastDFSClient;
import com.angel.core.util.JsonUtil;
import com.angel.core.util.MatcherUtil;
import com.angel.core.util.PDFUtils;
import com.angel.core.util.Pager;
import com.angel.core.util.PropertyConfUtil;
import com.angel.health.BuzAssessment;
import com.angel.health.BuzCustomer;
import com.angel.health.BuzExaminationParsingWithBLOBs;
import com.angel.health.BuzFactors;
import com.angel.health.BuzMedicalContent;
import com.angel.health.ln.Audit;
import com.angel.healthReport.HeathReport;
import com.angel.provider.health.BuzAssessmentProvider;
import com.angel.provider.health.BuzCustomerProvider;
import com.angel.provider.health.BuzExaminationParsingProvider;
import com.angel.provider.health.BuzFactorsProvider;
import com.angel.provider.health.BuzMedicalContentProvider;
import com.angel.provider.health.BuzRiskFactorsProvider;
import com.angel.provider.health.BuzSurveyProvider;
import com.github.pagehelper.StringUtil;

/**
 * @author 作者姓名 cheng
 * @version 创建时间：2016年9月28日 下午7:38:53 类说明
 */
@Controller
@RequestMapping("assessment")
public class BuzAssessmentController {
	@Autowired
	private BuzAssessmentProvider baProvider;
	@Autowired
	private BuzCustomerProvider bcProvider;
	@Autowired
	private BuzSurveyProvider buzSurveyProvider;
	@Autowired
	private BuzExaminationParsingProvider bwpProvider;
	@Autowired
	private BuzMedicalContentProvider bmcProvider;
	@Autowired
	private BuzRiskFactorsProvider brfProvider;
	@Autowired
	private BuzFactorsProvider bfProvider;

	@RequestMapping("index")
	public String index(HttpServletRequest request, BuzAssessment assessment, Pager pager) {
		assessment.setEnable(1);
		Pager bean = baProvider.findAll(assessment, pager);
		request.setAttribute("pager", bean);
		request.setAttribute("assessment", assessment);
		return "assessing/chronic_assessing";
	}

	/**
	 * 跳转到审核页面
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/auditPage/{id}")
	public String auditPage(@PathVariable("id") Integer id, HttpServletRequest req) {
		Audit audit = new Audit();
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		BuzAssessment ba = new BuzAssessment();
		ba.setId(id);
		audit.setBaId(id);
		ba = baProvider.findById(ba);
		BuzCustomer bc = new BuzCustomer();
		bc.setId(ba.getCustomerId());
		bc = bcProvider.findById(bc);
		// 问卷调查
		Map<String, String> buzSurvey = buzSurveyProvider.PDFByCustomerId(bc.getId().toString());
		Map<String, String> wjMap = HeathReport.getWj(buzSurvey);
		// 体检指标
		List<BuzMedicalContent> contentList = bmcProvider.findContentAll(null);
		Map<String, BuzMedicalContent> map = HeathReport.medicalContent(contentList);
		// 体检报告解析数据
		BuzExaminationParsingWithBLOBs bxp = new BuzExaminationParsingWithBLOBs();
		bxp.setId(ba.getExaminationParsingId());
		bxp = bwpProvider.findById(bxp);
		// 风险评估参数部分
		List<Map<String, Object>> riskFactorsList = brfProvider.findRiskFactors(null);
		// 危险因素分数
		List<BuzFactors> farctorsList = bfProvider.findAll(null);

		String assessmentCode = sdf.format(date).replace("年", "").replace("月", "").replace("日", "") + "0000000";
		assessmentCode = assessmentCode.substring(0, assessmentCode.length() - id.toString().length()) + id;
		audit.setAssessmentCode(assessmentCode);
		audit.setCustomerName(bc.getName());
		String customerSex = "";
		switch (bc.getSex()) {
		case 1:
			customerSex = "男";
			break;
		case 0:
			customerSex = wjMap.get("customerSex").trim();
			break;
		case 2:
			customerSex = "女";
			break;
		default:
			break;
		}
		audit.setCustomerSex(customerSex);
		audit.setAssessmentTime(sdf.format(date));

		String customerAge = wjMap.get("customerAge");
		if (MatcherUtil.isShu(customerAge)) {
			customerAge = Integer.parseInt(customerAge) > 200 ? (StringUtil.isEmpty(bc.getCardNumber()) ? "未提供"
					: (bc.getCardNumber().length() == 18
							? (new Date().getYear() - Integer.parseInt(bc.getCardNumber().substring(6, 10))) + ""
							: "未提供"))
					: customerAge;
		} else {
			customerAge = "未提供";
		}
		audit.setCustomerAge(customerAge);

		int sex = 1;
		if ("男".equals(customerSex)) {
			sex = 1;
		} else if ("女".equals(customerSex)) {
			sex = 2;
		} else {
			sex = 0;
		}
		Map<String, String> generateReport = HeathReport.generateReport(bxp.getMedical(),
				sdf.format(bxp.getMedicalTime()), map, sex);
		String medical = generateReport.get("medical");
		audit.setMedical(medical);
		String bmi = generateReport.get("bmi");// 体重指数
		audit.setWeightIndexNum(bmi);
		String des = HeathReport.getDes(Double.parseDouble(bmi));
		audit.setWeightIndex(des);
		
		Map<String,String> healthMap = HeathReport.health(bxp.getMedical(),wjMap,map,sex);
		audit.setImportantProblem(healthMap.get("importantProblem"));
		audit.setSecondaryProblem(healthMap.get("secondaryProblem"));
		audit.setGeneralProblem(healthMap.get("generalProblem"));
		// 风险评估得分
		int wjResult = 0;
		String zjdp = "";
		for (int type = 0; type < 5; type++) {// 0重要指标1.高血压2.脑卒中3.糖尿病4乳腺癌
			if (type == 4 && sex == 1) {
				// 男性乳腺癌没有数据
				audit.setRxaRiskFactors("");
				audit.setRxaResult("男性暂无评估");
				audit.setRxaResultImg("0");
				continue;
			}
			Map<String, String> rfMap = HeathReport.generateRiskFactors(riskFactorsList, type, bxp.getMedical(), wjMap,
					sex);
			String riskFactors = rfMap.get("html");
			rfMap.remove("html");
			String result ;
			if (type == 4) {
//				riskFactors = HeathReport.generateRiskFactorsRXA(riskFactors);
				result = HeathReport.getResultForRXA(rfMap, wjResult);
				audit.setRxaRiskFactors(riskFactors);
				audit.setRxaResult(result.split(":")[0]);
				audit.setRxaResultImg(result.split(":")[1]);
				if(Integer.parseInt(result.split(":")[1]) >=3){
					zjdp += "乳腺癌、";
				}
				continue;
			}
			result = HeathReport.getResult(rfMap, farctorsList, type, sex, wjResult);
			if (type == 0) {
				audit.setZyzbRiskFactors(riskFactors);
			} else if (type == 1) {
				audit.setGxyRiskFactors(riskFactors);
				audit.setGxyResult(result.split(":")[0]);
				audit.setGxyResultImg(result.split(":")[1]);
				if(Integer.parseInt(result.split(":")[1]) >=3){
					zjdp += "高血压、";
				}
			} else if (type == 2) {
				audit.setNczRiskFactors(riskFactors);
				audit.setNczResult(result.split(":")[0]);
				audit.setNczResultImg(result.split(":")[1]);
				if(Integer.parseInt(result.split(":")[1]) >=3){
					zjdp += "脑卒中、";
				}
			} else if (type == 3) {
				audit.setTnbRiskFactors(riskFactors);
				audit.setTnbResult(result.split(":")[0]);
				audit.setTnbResultImg(result.split(":")[1]);
				if(Integer.parseInt(result.split(":")[1]) >=3){
					zjdp += "糖尿病、";
				}
			} else if (type == 4) {
//				audit.setRxaRiskFactors(riskFactors);
//				audit.setRxaResult(result.split(":")[0]);
			}
		}
		if(!"".equals(zjdp)){
			audit.setZjdp(zjdp.substring(0,zjdp.length() -1 ));
		}
		req.setAttribute("audit", audit);
		return "assessing/auditPage";
	}
	
	@ResponseBody
	@RequestMapping("audit")
	public String audit(HttpServletRequest req){
		String bodyHtml = req.getParameter("bodyHtml");
		String customerName = req.getParameter("customerName");
		String baId = req.getParameter("baId");
		String path = req.getRealPath("");
		path = path.replaceAll("\\\\", "/");
		String serverName = StringUtil.isEmpty(req.getServletContext().getContextPath()) || "/".equals(req.getServletContext().getContextPath())?"":req.getServletContext().getContextPath();
		BuzAssessment ba = new BuzAssessment();
		ba.setId(Integer.parseInt(baId));
		StringBuffer html = new StringBuffer();
		html.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
		html.append("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
		html.append("<style type=\"text/css\">body {font-family: SimSun;margin:0px;padding:0px;font-size:14px;color:#323232}</style></head>");
		html.append("<body>");
		html.append(bodyHtml);
		html.append("</body></html>");
		
		UUID uid = UUID.randomUUID();
		
		PDFUtils.generatePdf(html.toString().replaceAll("imgy=\"imgy\"", "/").replaceAll(serverName+"/images/", ""), path, uid.toString(),req);
		FastDFSClient client;
		try {
			//生成成功后修改状态
			String fasedfs_url = PropertyConfUtil.getContextProperty(Constants.FASTDFS_UTL);
			Date date = new Date();
			client = new FastDFSClient();
			String pdfPath = client.uploadFile(path+"/pdf/"+uid+".pdf");
			System.err.println(pdfPath);
			ba.setAssessmentName(customerName+"健康报告");
			ba.setAssessmentTime(date);
			ba.setAssessmentUrl(fasedfs_url+pdfPath);
//			int up = baProvider.updateByCustomerId(ba);
			int up = baProvider.updateById(ba);
			if(up > 0){
				File _file = new File(path+"/pdf/"+uid.toString()+".pdf");
				if(_file.exists()){
					_file.delete();
				}
				return JsonUtil.toJson(fasedfs_url+pdfPath);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		return "";
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@ResponseBody
	@RequestMapping("del")
	public String del(String ids) {
		int delAll = baProvider.delAll(ids);
		if (delAll > 0) {
			return JsonUtil.toJson(delAll);
		} else {
			return JsonUtil.toJson(0);
		}
	}
}
